<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>兄弟组件通信</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
    <my-a></my-a>
    <my-b></my-b>
    <my-c></my-c>
</div>
<template id="a">
    <div>
        <h3>A组件: {{ name }}</h3>
        <button @click="send">将数据发送给C组件</button>
    </div>
</template>
<template id="b">
    <div>
        <h3>B组件: {{ age }}</h3>
        <button @click="send">将数据发送给C组件</button>
    </div>
</template>
<template id="c">
    <div>
        <h3>C组件: {{ name }},{{age}}</h3>
    </div>
</template>
<script>
const Event = new Vue(); //定义一个空的Vue实例
// A组件
let A = {
    template: '#a',
    data(){
        return{
            name: '姓名: 陈赫'
        }
    },
    methods:{
        send(){
            Event.$emit('data-a', this.name);
        }
    }
}
// B组件
let B = {
    template: '#b',
    data(){
        return{
            age: "年龄: 20"
        }
    },
    methods:{
        send(){
            Event.$emit('data-b', this.age);
        }
    }
}
//C组件
let C = {
    template: '#c',
    data(){
        return{
            name: "",
            age: ""
        }
    },
    mounted(){ //在模板编译完成后执行
        /*箭头函数内部不会产生新的this, 这边如果不用=>,
          this指代Event
         * */
        Event.$on('data-a', name => {
            this.name = name;
        })
        Event.$on('data-b', age => {
            this.age = age;
        })
    }
}

const app = new Vue({
    el: "#app",
    components: {
        'my-a': A,
        'my-b': B,
        'my-c': C
    }
});
</script>
</body>
</html>